/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-02-23 18:41:13
 * @LastEditTime: 2024-06-29 10:36:17
 * @FilePath: /nest_study/web/src/views/system/dept/index.tsx
 */
import { useEffect, useRef, useState } from "react";
import { TDeptInfo, TDeptSearch } from "./index.type";
import { Input, message, Modal, Table } from "antd";
import { columns } from "./columns";
import { getRowClassName, getTableScroll } from "@/utils/table";
import PageWrapper from "@/components/page_wrapper";
import TableSearch from "@/components/table_search";
import SearchItem from "@/components/search_item";
import { isValidKey } from "@/utils";
import { remoteList, removeInfo } from "@/api/system/dept";
import ShowInfo from "./components/info";

const Post = () => {
  //搜索初始化
  const searchParams: TDeptSearch = {
    name: '',
    page: 1,
  }
  const [scrollY, setScrollY] = useState(0)
  const formRef = useRef<any>();
  const [form, setForm] = useState<TDeptSearch>({ ...searchParams, size: 10 });
  //加载状态
  const [loading, setLoading] = useState<boolean>(false);
  //数据列表
  const [list, setList] = useState<TDeptInfo[]>([]);
  //数据总数
  const [total, setTotal] = useState<number>(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<Array<any>>([]);
  //显示创建 查看信息
  const [info, setInfo] = useState<TDeptInfo | null>();
  const [isShow, setIsShow] = useState<boolean>(false);

  useEffect(() => {
    setScrollY(getTableScroll())
    formRef.current = { ...form };
    search();
  }, [])
  //查询列表
  const search = async (page?: number) => {
    setLoading(true);
    setList([])
    setSelectedRowKeys([]);
    try {
      let newForm = { ...form, ...formRef.current }
      if (page) {
        changeItem(page, 'page');
        newForm.page = page;
      };
      let res = await remoteList(newForm);
      let { list, total } = res.data;
      setList(list || []);
      setTotal(total || 0)
    } finally {
      setLoading(false);
    }
  }
  //重置
  const reset = () => {
    for (let k in searchParams) {
      if (isValidKey(k, searchParams)) {
        formRef.current[k] = searchParams[k]
      }
    }
    setForm(formRef.current);
    search(1);
  }
  //添加 修改
  const dealInfo = (info?: TDeptInfo) => {
    setInfo(info);
    setIsShow(true);
  }
  //删除
  const remove = (info?: TDeptInfo) => {
    Modal.confirm({
      title: '删除操作',
      content: '确定要删除信息？',
      onOk: async () => {
        try {
          let ids = [];
          if (info) {
            ids = [info.id]
          } else {
            ids = [...selectedRowKeys];
          }
          await removeInfo(ids);
          message.success('操作成功');
          search();
          setSelectedRowKeys([]);
        } finally {
          Modal.destroyAll();
        }
      }
    })
  }
  //切换页数
  const changePage = (e: any) => {
    changeItem(e, 'page')
    search(e)
  }
  //参数变化
  const changeItem = (value: any, type: string) => {
    setForm({
      ...form,
      [type]: value
    })
    formRef.current[type] = value
  }
  //多选
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], _selectedRows: any[]) => {
      setSelectedRowKeys(selectedRowKeys);
    }
  };

  return (
    <PageWrapper>
      <>
        <TableSearch
          deletePerm={selectedRowKeys.length ? true : false}
          isExtra={true}
          add={() => dealInfo()}
          delete={() => remove()}
          search={() => search(1)}
          reset={() => reset()}
        >
          <SearchItem>
            <Input allowClear value={formRef.current?.name} onChange={(e) => changeItem(e.target.value, 'name')} placeholder="请输入部门名称" />
          </SearchItem>
        </TableSearch>
        <Table
          rowSelection={{
            type: "checkbox",
            columnWidth: 40,
            fixed: 'left',
            ...rowSelection,
            selectedRowKeys: selectedRowKeys
          }}
          columns={columns(
            (info: TDeptInfo) => dealInfo(info),
            (info: TDeptInfo) => remove(info))}
          dataSource={list}
          loading={loading}
          rowKey={'id'}
          sticky
          virtual
          scroll={{ x: 1000, y: scrollY }}
          rowClassName={getRowClassName}
          pagination={{
            size: formRef.current?.size,
            current: formRef.current?.page,
            total: total,
            showSizeChanger: true,
            onShowSizeChange: (_current: number, size: number) => changeItem(size, 'size'),
            showTotal: () => `共${total} 条`,
          }}
          onChange={(val) => changePage(val.current)}
        ></Table>
        {
          isShow && <ShowInfo info={info} close={() => setIsShow(false)} submit={() => { setIsShow(false); search() }} />
        }
      </>
    </PageWrapper>
  )
}

export default Post